package net.p2pcdn.email.service;

import net.p2pcdn.email.EmailSenderFailedException;
import net.p2pcdn.email.domain.EmailRecord;
import net.p2pcdn.email.domain.EmailType;
import net.p2pcdn.email.repository.EmailRecordDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import java.io.UnsupportedEncodingException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
public class DefaultEmailSender {
    private final static Logger _logger = LoggerFactory.getLogger(DefaultEmailSender.class);
    @Resource
    private EmailRecordDao emailRecordDao;
    @Value("${mailUser}")
    private String user;
    @Value("${mailPassWord}")
    private String password;
    @Value("${mailSendName}")
    private String sendName;
    @Value("${mailSmtpAuth}")
    private boolean auth;
    @Value("${mailSmtpHost}")
    private String smtpHost;
    @Autowired
    private MailConfig mailConfig;

    public void send(String acceptEmail, String subject, EmailType emailType, String content, String code) {
        try {
            JavaMailSender.sendMail(mailConfig, acceptEmail, subject, content);
            EmailRecord emailRecord = new EmailRecord();
            emailRecord.setId(UUID.randomUUID().toString());
            emailRecord.setAcceptEmail(acceptEmail);
            emailRecord.setCheckCode(code);
            emailRecord.setContent(content);
            emailRecord.setMailType(emailType.getType());
            emailRecordDao.insert(emailRecord);
        } catch (UnsupportedEncodingException | MessagingException e) {
            _logger.error("com.qc.email.DefaultEmailSender.send", e);
            throw new EmailSenderFailedException("邮件发送失败");
        }
    }

    public boolean validate(String acceptEmail, String code, EmailType emailType, int lifetime) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("acceptEmail", acceptEmail);
        map.put("checkCode", code);
        map.put("mailType", emailType.getType());
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, -lifetime);
        map.put("from", calendar.getTime());
        int count = emailRecordDao.queryByCheckCode(map);
        return count > 0;
    }
}
